package com.jph.simple;

import android.content.Intent;
import android.os.Message;
import android.os.Handler;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.google.protobuf.InvalidProtocolBufferException;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import adapter.MsgAdapter;
import common.SystemUtil;
import container.ChatManager;
import container.FriendManager;
import container.PlayerContainer;
import model.Friend;
import model.Msg;
import socket.ServerSession;
import utgame.UtMessage;
import utgame.UtMessage.MC_PlayerChat;
import utgame.UtMessage.MS_PlayerChat;
import utgame.UtMessage.MessagePacket.MessageType;


public class PlayerChatActivity extends TitleActivity{

    public static final String TAG = "PlayerChatActivity";

    public static final int ChatTypePlayer = 0;
    public static final int ChatTypeGroup = 1;

    public static final String ParamName = "name";
    public static final String ParamType = "type";

    private List<Msg> msgList = new ArrayList<>();
    private EditText inputText;
    private Button send;
    private RecyclerView msgRecyclerView;
    private MsgAdapter adapter;

    private String  mChatPlayerName;

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MessageType.PlayerChat_VALUE:
                    MS_PlayerChat chat = null;
                    try {
                        chat = MS_PlayerChat.parseFrom((byte[]) msg.obj);
                    } catch (InvalidProtocolBufferException e) {
                        e.printStackTrace();
                    }
                    if (chat == null) return;

                    if (!chat.getSenderName().equals(mChatPlayerName)){     // friend界面要显示小红点
                        ChatManager.getInstance().addChat(chat.getSenderName(), chat.getChatContent());
                        return;
                    }

                    msgList.add(new Msg(chat.getChatContent(), Msg.TYPE_RECEIVED, chat.getSenderName()));
                    adapter.notifyItemInserted(msgList.size() - 1);           //调用适配器的notifyItemInserted()用于通知列表有新的数据插入，这样新增的一条消息才能在RecyclerView中显示
                    msgRecyclerView.scrollToPosition(msgList.size() - 1);     //调用scrollToPosition()方法将显示的数据定位到最后一行，以保证可以看到最后发出的一条消息

                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player_chat);

        //从Intent 中获取数据
        Bundle bundle = this.getIntent().getExtras();
        mChatPlayerName = bundle.getString(ParamName);

        ServerSession.getInstance().addHandler(TAG, mHandler);

        setTitle(mChatPlayerName);
        showBackwardView(R.string.back, true);
        showForwardView(R.string.forward, true);

        initMsgs();                                                         //初始化消息数据
        inputText = (EditText) findViewById(R.id.input_text);
        send = (Button) findViewById(R.id.send);
        msgRecyclerView = (RecyclerView) findViewById(R.id.msg_recycler_view);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);    //LinearLayoutLayout即线性布局，创建对象后把它设置到RecyclerView当中
        msgRecyclerView.setLayoutManager(layoutManager);

        adapter = new MsgAdapter(msgList);                                    //创建MsgAdapter的实例并将数据传入到MsgAdapter的构造函数中
        msgRecyclerView.setAdapter(adapter);

        send.setOnClickListener(new View.OnClickListener() {                 //发送按钮点击事件
            @Override
            public void onClick(View v) {
                String content = inputText.getText().toString();              //获取EditText中的内容
                if (!"".equals(content)) {                                    //内容不为空则创建一个新的Msg对象，并把它添加到msgList列表中
                    Msg msg = new Msg(content, Msg.TYPE_SENT, PlayerContainer.getInstance().getName());
                    msgList.add(msg);
                    adapter.notifyItemInserted(msgList.size() - 1);           //调用适配器的notifyItemInserted()用于通知列表有新的数据插入，这样新增的一条消息才能在RecyclerView中显示
                    msgRecyclerView.scrollToPosition(msgList.size() - 1);     //调用scrollToPosition()方法将显示的数据定位到最后一行，以保证可以看到最后发出的一条消息
                    inputText.setText("");                                    //调用EditText的setText()方法将输入的内容清空

                    FriendManager.getInstance().getFriend(mChatPlayerName).addChat(msg);

                    if (!mChatPlayerName.equals(PlayerContainer.getInstance().getName())){
                        MC_PlayerChat.Builder builder = MC_PlayerChat.newBuilder();
                        builder.setReceiverName(mChatPlayerName);
                        builder.setChatContent(content);
                        ServerSession.getInstance().sendMessage(MessageType.PlayerChat, builder.build().toByteString());
                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ServerSession.getInstance().removeHandler(TAG);
    }

    private void initMsgs() {
        Friend friend = FriendManager.getInstance().getFriend(mChatPlayerName);
        List<Msg> chatList = friend.getChatList();

        // 离线消息
        UtMessage.MS_OfflineChat msOfflineChat = ChatManager.getInstance().getOfflineChat();
        if (msOfflineChat != null){
            List<com.google.protobuf.ByteString> offlineChatList = msOfflineChat.getOfflineChatList();
            for (com.google.protobuf.ByteString byteString : offlineChatList){
                UtMessage.OfflineChat offlineChat = null;
                try {
                    offlineChat = UtMessage.OfflineChat.parseFrom(byteString);
                } catch (InvalidProtocolBufferException e) {
                    e.printStackTrace();
                }

                List<UtMessage.ChatMsg> chatMsgList = offlineChat.getMsgList();
                if (!chatMsgList.isEmpty()){
                    if (mChatPlayerName.equals(chatMsgList.get(0).getSender())){
                        if (!chatMsgList.isEmpty()){

                            String time = null;
                            try {
                                // 模拟器需要+8h   手机正常
//                                time = SystemUtil.longToString(chatMsgList.get(0).getTime() + 8 * 3600 * 1000, "yyyy-MM-dd HH:mm:ss");
                                time = SystemUtil.longToString(chatMsgList.get(0).getTime(), "yyyy-MM-dd HH:mm:ss");
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            chatList.add(new Msg(time, Msg.TYPE_TIME, ""));
                        }
                        for (UtMessage.ChatMsg chatMsg : chatMsgList){
                            chatList.add(new Msg(chatMsg.getContent(), Msg.TYPE_RECEIVED, chatMsg.getSender()));
                        }
                        break;
                    }
                }
            }
            ChatManager.getInstance().setOfflineChat(null);
        }

        msgList.clear();
        for (Msg chat : chatList){
            msgList.add(new Msg(chat.getContent(), chat.getType(), chat.getSenderName()));
        }

        ChatManager.getInstance().clearChat(mChatPlayerName);

    }

    protected void onBackward(View backwardView){
        backToFriend();
    }

    @Override
    public void onBackPressed() {
//        super.onBackPressed();
        backToFriend();
    }

    private void backToFriend(){
        startActivity(new Intent(this, MainActivity.class));
        finish();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }
}
